/**
 * Created by user on 17/2/13.
 */
let FutuHttpClient = require('@futu/httpclient');
let FutuHttpRequest = require('@futu/httpclient').FutuHttpRequest;

let utils = require('../utils');
let AuthUser = require('../models/AuthUser');//user的数据模型及一个实例化函数

module.exports = () => {
    let logger = utils.getLogger();
    return async (ctx, next) => {
        let authUser = ctx.session.authUser;
        let AUTH_TICKET = ctx.request.query.AUTH_TICKET;//请求携带的参数
        logger.debug('session is: ' + JSON.stringify(ctx.session, null, 2));
        if (authUser && !authUser.isGuest) {
            await next();
            return;
        }
        if (AUTH_TICKET) {
            let domain = ctx.request.hostname;
            let client = await FutuHttpClient.getInstanceByEndpoint();
            let request = new FutuHttpRequest(
                `http://passport.oa.com/site/validate-ticket.html?AUTH_TICKET=${AUTH_TICKET}&AUTH_DOMAIN=${domain}`);
            let response = await client.request('get', request);
            if (response.httpStatusCode !== 200) {
                throw new Error('login by passport failed' + response.message);
            }
            let data = JSON.parse(response.data || '{}');
            if (data.result !== 0) {
                throw new Error('login by passport failed' + response.message);
            }
            let user = data.data.user_info;
            ctx.session.oa_token = data.data.oa_token;
            ctx.session.oa_token_init_time = data.data.oa_token_init_time;
            ctx.session.oa_token_invalid_time = data.data.oa_token_invalid_time;
            ctx.session.authUser = new AuthUser();
            ctx.session.authUser.isGuest = false;
            ctx.session.authUser.setUser(user);
            logger.debug(JSON.stringify(response));
        }

        await next();
    };
};
